

#include "pistol.h"
#include "bullet.h"
#include "gamemanager.h"
#include "army.h"
#include "CCSkeletalSprite.h"
#include "gamescene.h"

#define __super         Unit

Pistol::Pistol() {

}

Pistol::~Pistol() {

}

void Pistol::init(UnitInfo const &info, float unitScale) {
	__super::init(info, unitScale);
}

void Pistol::update(float ticks) {
	__super::update(ticks);
}

void Pistol::handleStateBirth(float ticks) {
	transformState(UnitState::idle);
}

void Pistol::handleStateDying(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::died);
	}
}

void Pistol::handleStateAim(float ticks) {

}

void Pistol::handleStateAttack(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::idle);
	}
}

void Pistol::handleStateIdle(float ticks) {
	if (gameScene->battleState == BattleState::standby) {
		return;
	}

	if (_timeElapsed >= attribute.reloadTime) {
		if (gridInfo.globalLineIndex == ourArmy->frontLine && target) {
			transformState(UnitState::attack);
		} else {
			if (findDistantOpponent()) {
				transformState(UnitState::attack);
			}
		}
	}
}

void Pistol::handleStateReload(float ticks) {
}

void Pistol::handleStateWalk(float ticks) {
	if (gameScene->battleState == BattleState::standby) {
		transformState(UnitState::idle);
	} else {
		move(ticks);

		if (arrivedTargetPosition) {
			transformState(UnitState::idle);
		} else if (_timeElapsed >= attribute.reloadTime) {
			if (findDistantOpponent()) {
				transformState(UnitState::walk_attack);
			}
		}
	}
}

void Pistol::handleStateWalkAim(float ticks) {

}

void Pistol::handleStateWalkAttack(float ticks) {
	move(ticks);

	if (sprite->animationIsDone()) {
		if (arrivedTargetPosition) {
			transformState(UnitState::idle);
		} else {
			transformState(previousState);
		}
	}
}

void Pistol::handleStateWalkReload(float ticks) {

}

void Pistol::onAttack() {
	Unit *enemy = nullptr;
	if (gridInfo.globalLineIndex == ourArmy->frontLine) {
		enemy = target;
	} else {
		enemy = findDistantOpponent();
	}

	if (enemy) {
		auto from = sprite->getBonePositionRelativeToWorld("skeleton_head");
		auto to = enemy->sprite->getBonePositionRelativeToWorld("skeleton_head");
		to.y = from.y;
		Bullet *bullet = new Bullet(&attribute);
		bullet->init();
		enemy->addBullet(bullet);
	}

	_timeElapsed = 0;
}

void Pistol::moveTo(const CCPoint &pos) {
	__super::moveTo(pos);

	transformState(UnitState::walk);
}

void Pistol::startAttack() {
	__super::startAttack();
}
